<?php
/**
 * @file CrontabMonitor.php
 * @author CaoQiCheng
 * @date 2016年4月26日 下午17:16:11
 * @brief 
 */

namespace haibao\cms\data\crontab;

class CrontabMonitor extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\crontab\CrontabMonitor');
    }
    
    /**
     * 添加任务
     */
    public function saveCrontab($crontabModel,$isEdit){
    	if(!$crontabModel){
    		return false;
    	}
    	if($isEdit){
    		$this->save($crontabModel);
    	}else {
    		$this->add($crontabModel);
    	}
    
    	return $crontabModel;
    }

    /**
     * 删除任务
     */
    public function delCrontab($crontabId){
    	if(!$crontabId){
    		return false;
    	}
    	$this->query('delete from `CrontabMonitor` where Id = %s', array(
    			$crontabId
    	));
    }
    
    /**
     * 获取计划任务规定的查询列表
     */
    public function getTableList($crontabInfo){
    	if(!$crontabInfo){
    		return false;
    	}
    	
    	if($crontabInfo->MonitorWhere && !is_null(json_decode($crontabInfo->MonitorWhere))){
    		$monitorWhere = json_decode($crontabInfo->MonitorWhere);
    		if(isset($monitorWhere->sql) && isset($monitorWhere->where)){
    			$sql = $monitorWhere->sql;
    			$value = $monitorWhere->where;
    			$valarr = explode(',', str_replace('，', ',', $value));
    			
    			$result = $this->query($sql,$valarr);
    			
    		}else {
    			$sql = 'select Id,'.$crontabInfo->MonitorParam.' from '.$crontabInfo->MonitorTable.' ';
    			$sql .= ' order by '.$crontabInfo->MonitorParam.' desc';
    			$result = $this->query($sql);
    		}
    	}else {
    		$sql = 'select Id,'.$crontabInfo->MonitorParam.' from '.$crontabInfo->MonitorTable.' ';
    		$sql .= ' order by '.$crontabInfo->MonitorParam.' desc';
    		$result = $this->query($sql);
    	}
    
    	$data = $table = array();
    	while($result->fetch_assoc()){
    		$table['Id'] = $result->getData('Id');
    		$table['Param'] = $result->getData($crontabInfo->MonitorParam);
    		array_push($data, $table);
    	}
    	return array(
    			'data'=>$data,
    	);
    	
    }

}